/**
 * 库存物品 列表页 JS 脚本
 * @author 金杰 , maillank@qq.com
 * @since 2022-04-22 05:33:06
 */

function FormPage() {

    var settings,admin,form,table,layer,util,fox,upload,xmSelect,foxup;
    const moduleURL="/service-eam/eam-goods-stock";
    // 表单执行操作类型：view，create，edit
    var action=null;
    var disableCreateNew=false;
    var disableModify=false;
    var dataBeforeEdit=null;
    /**
     * 入口函数，初始化
     */
    this.init=function(layui) {
        admin = layui.admin,settings = layui.settings,form = layui.form,upload = layui.upload,foxup=layui.foxnicUpload;
        laydate = layui.laydate,table = layui.table,layer = layui.layer,util = layui.util,fox = layui.foxnic,xmSelect = layui.xmSelect;

        action=admin.getTempData('eam-goods-stock-form-data-form-action');
        //如果没有修改和保存权限
        if( !admin.checkAuth(AUTH_PREFIX+":update") && !admin.checkAuth(AUTH_PREFIX+":save")) {
            disableModify=true;
        }
        if(action=="view") {
            disableModify=true;
        }

        if(window.pageExt.form.beforeInit) {
            window.pageExt.form.beforeInit(action,admin.getTempData('eam-goods-stock-form-data'));
        }

        //渲染表单组件
        renderFormFields();

        //填充表单数据
        fillFormData();

        //绑定提交事件
        bindButtonEvent();

    }

    /**
     * 自动调节窗口高度
     * */
    var adjustPopupTask=-1;
    function adjustPopup() {
        if(window.pageExt.form.beforeAdjustPopup) {
            var doNext=window.pageExt.form.beforeAdjustPopup();
            if(!doNext) return;
        }

        clearTimeout(adjustPopupTask);
        var scroll=$(".form-container").attr("scroll");
        if(scroll=='yes') return;
        adjustPopupTask=setTimeout(function () {
            var body=$("body");
            var bodyHeight=body.height();
            var footerHeight=$(".model-form-footer").height();
            var area=admin.changePopupArea(null,bodyHeight+footerHeight,'eam-goods-stock-form-data-win');
            if(area==null) return;
            admin.putTempData('eam-goods-stock-form-area', area);
            window.adjustPopup=adjustPopup;
            if(area.tooHeigh) {
                var windowHeight=area.iframeHeight;
                var finalHeight=windowHeight-footerHeight-16;
                //console.log("windowHeight="+windowHeight+',bodyHeight='+bodyHeight+",footerHeight="+footerHeight+",finalHeight="+finalHeight);
                $(".form-container").css("display","");
                $(".form-container").css("overflow-y","scroll");
                $(".form-container").css("height",finalHeight+"px");
                $(".form-container").attr("scroll","yes");
            }
        },250);
    }

    /**
     * 渲染表单组件
     */
    function renderFormFields() {
        fox.renderFormInputs(form);

        //渲染 categoryId 下拉字段
        fox.renderSelectBox({
            el: "categoryId",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("categoryId",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "hierarchyName", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].hierarchyName,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 status 下拉字段
        fox.renderSelectBox({
            el: "status",
            radio: true,
            filterable: false,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("status",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            transform:function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    opts.push({data:data[i],name:data[i].text,value:data[i].code,selected:(defaultValues.indexOf(data[i].code)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 manufacturerId 下拉字段
        fox.renderSelectBox({
            el: "manufacturerId",
            radio: true,
            filterable: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("manufacturerId",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "manufacturerName", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].manufacturerName,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 brandId 下拉字段
        fox.renderSelectBox({
            el: "brandId",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("brandId",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "brandName", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].brandName,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染图片字段
        foxup.render({
            el:"pictureId",
            maxFileCount: 1,
            displayFileName: false,
            accept: "image",
            acceptMime:'image/*',
            exts:'png|jpg|bmp|gif|jpeg',
            afterPreview:function(elId,index,fileId,upload,fileName,fileType){
                adjustPopup();
                window.pageExt.form.onUploadEvent &&  window.pageExt.form.onUploadEvent({event:"afterPreview",elId:elId,index:index,fileId:fileId,upload:upload,fileName:fileName,fileType:fileType});
            },
            afterUpload:function (elId,result,index,upload) {
                console.log("文件上传后回调");
                window.pageExt.form.onUploadEvent &&  window.pageExt.form.onUploadEvent({event:"afterUpload",elId:elId,index:index,upload:upload});
            },
            beforeRemove:function (elId,fileId,index,upload) {
                console.log("文件删除前回调");
                if(window.pageExt.form.onUploadEvent) {
                    return window.pageExt.form.onUploadEvent({event:"beforeRemove",elId:elId,index:index,fileId:fileId,upload:upload});
                }
                return true;
            },
            afterRemove:function (elId,fileId,index,upload) {
                adjustPopup();
                window.pageExt.form.onUploadEvent &&  window.pageExt.form.onUploadEvent({event:"afterRemove",elId:elId,index:index,upload:upload});
            }
        });
        //渲染 sourceId 下拉字段
        fox.renderSelectBox({
            el: "sourceId",
            radio: true,
            filterable: false,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("sourceId",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "purchase".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].label,value:data[i].code,selected:(defaultValues.indexOf(data[i].code)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 goodsId 下拉字段
        fox.renderSelectBox({
            el: "goodsId",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("goodsId",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "name", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].name,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        laydate.render({
            elem: '#storageDate',
            format:"yyyy-MM-dd",
            trigger:"click",
            done: function(value, date, endDate){
                window.pageExt.form.onDatePickerChanged && window.pageExt.form.onDatePickerChanged("storageDate",value, date, endDate);
            }
        });
        //渲染 goodsModel 下拉字段
        fox.renderSelectBox({
            el: "goodsModel",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("goodsModel",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "model", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].model,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 goodsUnit 下拉字段
        fox.renderSelectBox({
            el: "goodsUnit",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("goodsUnit",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "unit", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].unit,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 goodsCode 下拉字段
        fox.renderSelectBox({
            el: "goodsCode",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("goodsCode",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "code", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].code,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
        //渲染 goodsBarCode 下拉字段
        fox.renderSelectBox({
            el: "goodsBarCode",
            radio: true,
            filterable: true,
            paging: true,
            pageRemote: true,
            on: function(data){
                setTimeout(function () {
                    window.pageExt.form.onSelectBoxChanged && window.pageExt.form.onSelectBoxChanged("goodsBarCode",data.arr,data.change,data.isAdd);
                },1);
            },
            //转换数据
            searchField: "barCode", //请自行调整用于搜索的字段名称
            extraParam: {}, //额外的查询参数，Object 或是 返回 Object 的函数
            transform: function(data) {
                //要求格式 :[{name: '水果', value: 1},{name: '蔬菜', value: 2}]
                var defaultValues=[],defaultIndexs=[];
                if(action=="create") {
                    defaultValues = "".split(",");
                    defaultIndexs = "".split(",");
                }
                var opts=[];
                if(!data) return opts;
                for (var i = 0; i < data.length; i++) {
                    if(!data[i]) continue;
                    opts.push({data:data[i],name:data[i].barCode,value:data[i].id,selected:(defaultValues.indexOf(data[i].id)!=-1 || defaultIndexs.indexOf(""+i)!=-1)});
                }
                return opts;
            }
        });
    }

    /**
     * 填充表单数据
     */
    function fillFormData(formData) {
        if(!formData) {
            formData = admin.getTempData('eam-goods-stock-form-data');
        }

        window.pageExt.form.beforeDataFill && window.pageExt.form.beforeDataFill(formData);

        var hasData=true;
        //如果是新建
        if(!formData || !formData.id) {
            adjustPopup();
            hasData=false;
        }
        var fm=$('#data-form');
        if (hasData) {
            fm[0].reset();
            form.val('data-form', formData);

            //设置 图片 显示附件
            if($("#pictureId").val()) {
                foxup.fill("pictureId",$("#pictureId").val());
            } else {
                adjustPopup();
            }






            //处理fillBy

            //
            fm.attr('method', 'POST');
            fox.fillDialogButtons();
            renderFormFields();

            window.pageExt.form.afterDataFill && window.pageExt.form.afterDataFill(formData);

        }

        //渐显效果
        fm.css("opacity","0.0");
        fm.css("display","");
        setTimeout(function (){
            fm.animate({
                opacity:'1.0'
            },100);
        },1);

        //禁用编辑
        if((hasData && disableModify) || (!hasData &&disableCreateNew)) {
            fox.lockForm($("#data-form"),true);
            $("#submit-button").hide();
            $("#cancel-button").css("margin-right","15px")
        } else {
            $("#submit-button").show();
            $("#cancel-button").css("margin-right","0px")
        }

        //调用 iframe 加载过程
        var formIfrs=$(".form-iframe");
        for (var i = 0; i < formIfrs.length; i++) {
            var jsFn=$(formIfrs[i]).attr("js-fn");
            if(window.pageExt.form){
                jsFn=window.pageExt.form[jsFn];
                jsFn && jsFn($(formIfrs[i]),$(formIfrs[i])[0].contentWindow,formData);
            }
        }

        dataBeforeEdit=getFormData();

    }

    function getFormData() {
        var data=form.val("data-form");




        return data;
    }

    function verifyForm(data) {
        return fox.formVerify("data-form",data,VALIDATE_CONFIG)
    }

    function saveForm(param) {
        param.dirtyFields=fox.compareDirtyFields(dataBeforeEdit,param);
        var api=moduleURL+"/"+(param.id?"update":"insert");
        admin.post(api, param, function (data) {
            if (data.success) {
                var doNext=true;
                if(window.pageExt.form.betweenFormSubmitAndClose) {
                    doNext=window.pageExt.form.betweenFormSubmitAndClose(param,data);
                }
                if(doNext) {
                    admin.finishPopupCenterById('eam-goods-stock-form-data-win');
                }
            } else {
                fox.showMessage(data);
            }
            window.pageExt.form.afterSubmit && window.pageExt.form.afterSubmit(param,data);
        }, {delayLoading:1000,elms:[$("#submit-button")]});
    }

    /**
     * 保存数据，表单提交事件
     */
    function bindButtonEvent() {

        form.on('submit(submit-button)', function (data) {
            //debugger;
            data.field = getFormData();

            if(window.pageExt.form.beforeSubmit) {
                var doNext=window.pageExt.form.beforeSubmit(data.field);
                if(!doNext) return ;
            }
            //校验表单
            if(!verifyForm(data.field)) return;

            saveForm(data.field);
            return false;
        });

        // 请选择公司对话框
        $("#ownCompanyId-button").click(function(){
            var ownCompanyIdDialogOptions={
                field:"ownCompanyId",
                formData:getFormData(),
                inputEl:$("#ownCompanyId"),
                buttonEl:$(this),
                single:true,
                //限制浏览的范围，指定根节点 id 或 code ，优先匹配ID
                root: "",
                targetType:"com",
                prepose:function(param){ return window.pageExt.form.beforeDialog && window.pageExt.form.beforeDialog(param);},
                callback:function(param,result){ window.pageExt.form.afterDialog && window.pageExt.form.afterDialog(param,result);}
            };
            fox.chooseOrgNode(ownCompanyIdDialogOptions);
        });
        // 请选择组织节点对话框
        $("#useOrgId-button").click(function(){
            var useOrgIdDialogOptions={
                field:"useOrgId",
                formData:getFormData(),
                inputEl:$("#useOrgId"),
                buttonEl:$(this),
                single:true,
                //限制浏览的范围，指定根节点 id 或 code ，优先匹配ID
                root: "",
                targetType:"org",
                prepose:function(param){ return window.pageExt.form.beforeDialog && window.pageExt.form.beforeDialog(param);},
                callback:function(param,result){ window.pageExt.form.afterDialog && window.pageExt.form.afterDialog(param,result);}
            };
            fox.chooseOrgNode(useOrgIdDialogOptions);
        });
        // 请选择人员对话框
        $("#managerId-button").click(function(){
            var managerIdDialogOptions={
                field:"managerId",
                formData:getFormData(),
                inputEl:$("#managerId"),
                buttonEl:$(this),
                single:true,
                //限制浏览的范围，指定根节点 id 或 code ，优先匹配ID
                root: "",
                targetType:"emp",
                prepose:function(param){ return window.pageExt.form.beforeDialog && window.pageExt.form.beforeDialog(param);},
                callback:function(param,result){ window.pageExt.form.afterDialog && window.pageExt.form.afterDialog(param,result);}
            };
            fox.chooseEmployee(managerIdDialogOptions);
        });
        // 请选择人员对话框
        $("#originatorId-button").click(function(){
            var originatorIdDialogOptions={
                field:"originatorId",
                formData:getFormData(),
                inputEl:$("#originatorId"),
                buttonEl:$(this),
                single:true,
                //限制浏览的范围，指定根节点 id 或 code ，优先匹配ID
                root: "",
                targetType:"emp",
                prepose:function(param){ return window.pageExt.form.beforeDialog && window.pageExt.form.beforeDialog(param);},
                callback:function(param,result){ window.pageExt.form.afterDialog && window.pageExt.form.afterDialog(param,result);}
            };
            fox.chooseEmployee(originatorIdDialogOptions);
        });

        //关闭窗口
        $("#cancel-button").click(function(){ admin.finishPopupCenterById('eam-goods-stock-form-data-win'); });

    }

    window.module={
        getFormData: getFormData,
        verifyForm: verifyForm,
        saveForm: saveForm,
        fillFormData: fillFormData,
        adjustPopup: adjustPopup,
        action: action,
        setAction: function (act) {
            action = act;
        }
    };

    window.pageExt.form.ending && window.pageExt.form.ending();

}

layui.use(['form', 'table', 'util', 'settings', 'admin', 'upload','foxnic','xmSelect','foxnicUpload','laydate'],function() {
    var task=setInterval(function (){
        if(!window["pageExt"]) return;
        clearInterval(task);
        (new FormPage()).init(layui);
    },1);
});